<?php
/**
 * @Name: base文件
 * @Author: Zhaojun
 * @Date:   2018-03-26 15:54:31
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-03-17 12:53:03
 */

namespace app\actstar\controller;
use app\common\controller\WapBase;
use think\facade\Config as thinkConfig;

class ActstarBase extends WapBase {

	protected $configInfo;

	protected $cookieOpenidName;
	protected $cookieAccessTokenName;

	protected $moondb;
	protected $moonuid;
	protected $moonpwuid;
	protected $moonname;
	protected $moonavatar;

	function initialize() {
		parent::initialize();

		$this->configDao = model('actstar_manage/Config');
		$this->userDao = model('actstar_manage/User');

		//用户登陆相关
		$this->cookieOpenidName = 'actstar_openid4';
		$this->cookieUnionidName = 'actstar_unionid4';
		$this->cookieAccessTokenName = 'actstar_accesstoken4';

		//读取manage中的配置
		$moduleconfig = require_once(APP_PATH.'actstar_manage/config/moduleconfig.php');
		config($moduleconfig, 'moduleconfig');
		
		\think\facade\Config::load(APP_PATH.'actstar_manage/common.php');
		
		//保存和获取配置
		$this->saveAndGetConfig();

		//自定义底部菜单
// 		if ($this->configInfo['isopen_footermenu']) {
// 			$this->getFootermenu();
// 		}

		//授权获取用户信息
		$this->setWeixinAndGetUser();
	}

	function saveAndGetConfig() {
		$sys_identify = config('sys_identify');
		$configInfo = cache($sys_identify);
		if (empty($configInfo)) {
			$configInfo = $this->configDao->getConfigsBySpace('global');
			$configInfo['shop_logo'] = config('app.ftp_web').$configInfo['shop_logo'];
			$configInfo['kefu_ewm'] = config('app.ftp_web').$configInfo['kefu_ewm'];
			$configInfo['share_icon'] = config('app.ftp_web').$configInfo['share_icon'];
			cache($sys_identify, $configInfo, 3600);
		}
		//print_r($configInfo);
		thinkConfig::set($configInfo); //添加系统配置
		$this->configInfo = $configInfo;
		$this->assign('configInfo', $configInfo);
		
		//缓存相关,获取公告列表
		$announceDao = model('actstar_manage/Announce');
		$announceList = $announceDao->getCacheList();
		//print_r($announceList);
		$this->assign('announceList', $announceList);
		
		//缓存相关,获取弹出公告牌
		$bulletinDao = model('actstar_manage/Bulletin');
		$bulletinInfo = $bulletinDao->getCacheInfo();
		//print_r($bulletinInfo);
		$this->assign('bulletinInfo', $bulletinInfo);
	}

// 	function getFootermenu() {
// 		$footermenuDao = model('actstar_manage/Footermenu');
// 		list($footermenuList) = $footermenuDao->getFrontList();
// 		//print_r($footermenuList);
// 		$this->assign('footermenuList', $footermenuList);
// 	}

	/**
	 * 微信用户授权和获得app用户
	 */
	public function setWeixinAndGetUser() {
		$nowTime = $this->ts;

		if ($this->isWeixin) { //微信
			//微信账号
			$weixinAccountDao = model('weixin_manage/WeixinAccount');
			$wxdb = $weixinAccountDao->getInfo(2); //昆山全知道
			//print_r($wxdb);

			//微信jssdk
			$jssdk = new \org\weixin\jssdk($wxdb['appid'], $wxdb['appsecret'], $wxdb['wxnumber']);
			$signPackage = $jssdk->getSignPackage();
			$this->assign('signPackage', $signPackage);
			//微信jssdk end

			//获取缓存中的access_token
			$access_token = $jssdk->getAccessTokenForOut();

			$options = array(
				'token'=>$wxdb['token'], //填写你设定的key
				'encodingaeskey'=>$wxdb['aeskey'], //填写加密用的EncodingAESKey
				'appid'=>$wxdb['appid'], //填写高级调用功能的app id, 请在微信开发模式后台查询
				'appsecret'=>$wxdb['appsecret'], //填写高级调用功能的密钥
				'partnerid'=>'', //财付通商户身份标识，支付权限专用，没有可不填
				'partnerkey'=>'', //财付通商户权限密钥Key，支付权限专用
				'paysignkey'=>'' //商户签名密钥Key，支付权限专用
			);
			$weObj = new \wechat\Wechat($options);

			//使用jssdk获取到的access_token赋值，下文要用
			$weObj->checkAuth('', '', $access_token);

			$openid = cookie($this->cookieOpenidName);
			//$unionid = cookie($this->cookieUnionidName);
			$user_access_token = cookie($this->cookieAccessTokenName);

			if (empty($openid) || empty($user_access_token)) {
				//获取openid、access_token
				$json = $weObj->getOauthAccessToken();
				db('Aaaa')->insert(['space'=>'actstar', 'flag'=>'json', 'content'=>pw_var_export($json)]);
				$openid = $json['openid'];
				$unionid = $json['unionid'];
				$user_access_token = $json['access_token'];
				$expires_in = $json['expires_in'];
				$expires_in = '1800'; //7200秒，2小时，但是我改短一点。

				db('Aaaa')->insert(array('space'=>'actstar', 'flag'=>'openid', 'content'=>'', 'extra'=>$openid, 'extra2'=>$user_access_token));

				if (empty($openid)) { //通过微信接口获取不到openid，则继续获取
					$callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
					$url = $weObj->getOauthRedirect($callback, 1); //请求微信接口，通过oauth2认证获得来访用户的code值
					header("Location:".$url);exit;
				} else {
					cookie($this->cookieOpenidName, $openid, $expires_in);
					//cookie($this->cookieUnionidName, $unionid, $expires_in);
					cookie($this->cookieAccessTokenName, $user_access_token, $expires_in);
				}
			}

			//$userInfo = $this->userDao->getInfoByUnionid($unionid); //根据unionid获取用户信息
			$userInfo = $this->userDao->getInfoByOpenid($openid); //根据openid获取用户信息
			//print_r($userInfo);exit;

			if (!$userInfo) { //=====用户不存在
				$wxUserInfo = $weObj->getOauthUserinfo($user_access_token, $openid);
				if ($wxUserInfo === false) {
					$this->reportOauthUserinfo($weObj, $wxdb);
				}

				$data = array(
					'openid'			=> $openid,
					'unionid'			=> (string) $wxUserInfo['unionid'],
					'username'			=> $wxUserInfo['nickname'],
					'avatar'			=> $wxUserInfo['headimgurl'],
					'gender'			=> $wxUserInfo['sex'],
					'city'				=> $wxUserInfo['city'],
					'last_login_time'	=> $nowTime,
				);
				$data['create_time'] = $nowTime;

				//验证用户是否关注
				if (1) {
					$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
					if ($wxUserInfo2 !== false) {
						$data['subscribe'] = $wxUserInfo2['subscribe'];
					}
				}

				$id = $this->userDao->baseAddData($data); //插入用户数据
				$moondb = $data;
				$moondb['from'] = 'wx-add';
				$moondb['id'] = $id;
				$moondb['source'] = 'wx';
			} else if ($nowTime - $userInfo['last_login_time'] > $this->weixinUserUpdateInterval) { //=====更新用户数据
				$wxUserInfo = $weObj->getOauthUserinfo($user_access_token, $openid);
				if ($wxUserInfo === false) {
					$this->reportOauthUserinfo($weObj, $wxdb);
				}

				$data = array(
					'openid'			=> $openid,
					'unionid'			=> (string) $wxUserInfo['unionid'],
					'username'			=> $wxUserInfo['nickname'],
					'avatar'			=> $wxUserInfo['headimgurl'],
					'gender'			=> $wxUserInfo['sex'],
					'city'				=> $wxUserInfo['city'],
					'last_login_time'	=> $nowTime,
				);

				//验证用户是否关注
				if (1) {
					$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
					if ($wxUserInfo2 !== false) {
						$data['subscribe'] = $wxUserInfo2['subscribe'];
					}
				}

				$this->userDao->baseUpdateData($userInfo['id'], $data); //更新用户数据
				$moondb = $userInfo;
				$moondb['from'] = 'wx-update';
				$moondb['id'] = $userInfo['id'];
				$moondb['source'] = 'wx';
			} else {
				$moondb = $userInfo;
				$moondb['from'] = 'wx-other';
				$moondb['source'] = 'wx';

				//用户没有关注的情况
				if (1 && $moondb['subscribe'] == 0) {
					$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
					if ($wxUserInfo2 !== false) {
						$data = [
							'subscribe'		=> $wxUserInfo2['subscribe']
						];
						$this->userDao->baseUpdateData($userInfo['id'], $data);
						$moondb['subscribe'] = $wxUserInfo2['subscribe'];
					}
				}
			}
		} else { //app及其他
			if ($this->phpwinduid) {
				$userInfo = $this->userDao->getInfoByPwuid($this->phpwinduid); //根据uid获取用户信息

				if (!$userInfo) { //=====用户不存在
					$data = array(
						'username'			=> $this->phpwindid,
						'avatar'			=> $this->phpwinddb['avatar'],
						'last_login_time'	=> $nowTime
					);
					$data['pwuid'] = $this->phpwinduid;
					$data['create_time'] = $nowTime;

					$id = $this->userDao->baseAddData($data); //插入用户数据
					$moondb = $data;
					$moondb['id'] = $id;
					$moondb['from'] = 'app-add';
					$moondb['source'] = 'app';
				} else if ($nowTime - $userInfo['last_login_time'] > $this->weixinUserUpdateInterval) { //=====更新用户数据
					$data = array(
						'username'			=> $this->phpwindid,
						'avatar'			=> $this->phpwinddb['avatar'],
						'last_login_time'	=> $nowTime,
					);

					$this->userDao->baseUpdateData($userInfo['id'], $data); //更新用户数据
					$moondb = $data;
					$moondb['id'] = $userInfo['id'];
					$moondb['pwuid'] = $this->phpwinduid;
					$moondb['openid'] = '';
					$moondb['from'] = 'app-update';
					$moondb['source'] = 'app';
				} else {
					$moondb = $userInfo;
					$moondb['from'] = 'app-other';
					$moondb['source'] = 'app';
				}
			} else {
				$moondb = array(
					'from'		=> 'app-none',
					'id'		=> 0,
					'pwuid'		=> 0,
					'username'	=> '游客',
					'avatar'	=> '/tplnew/public/images/avatar/none.gif',
					'mobile'	=> '',
				);
			}
		}
		$moondb['uid'] = $moondb['id']; //把id赋值成uid
		//print_r($moondb);exit;

		$this->moonuid = $moondb['uid'];
		$this->moonpwuid = $moondb['pwuid'];
		$this->moonname = $moondb['username'];
		$this->moonavatar = $moondb['avatar'];
		$this->moondb = $moondb;
		$this->assign('moondb', $moondb);
		
		//用户经纬度相关
		if ($moondb['longitude']) {
			$this->assign('myLongitude', $moondb['longitude']);
			$this->assign('myLatitude', $moondb['latitude']);
			$this->assign('myAccuracy', $moondb['accuracy']);
			$this->assign('myLocationRemain', $this->ts - $moondb['location_time']);
		} else {
			$this->assign('myLongitude', 0);
			$this->assign('myLatitude', 0);
			$this->assign('myAccuracy', 0);
			$this->assign('myLocationRemain', 0);
		}
	}

}